<template>
  <div>
    <div class="search">
        <div class="input">
            <label>ID：</label><el-input v-model="searchorgId" placeholder="请输入ID" label="条件"></el-input>
            <label>编码：</label><el-input v-model="orgCode" placeholder="请输入编码" label="条件"></el-input>
            <label>名称：</label><el-input v-model="orgName" placeholder="请输入名称" label="条件"></el-input>
            <el-button type="primary" class="se" @click="search">搜索</el-button>
        </div>
    </div>
    <div class="add">
       <el-button type="primary" @click="dialogs">新增机构</el-button>
       <el-button type="danger" @click="dels">批量删除</el-button>
       <el-button type="warning" @click="staff">机构员工管理(关联员工)</el-button>
       <el-button type="warning">机构权限管理(关联角色)</el-button>
    </div>
    <div class="table">
        <tableVue :list="list" :state="true" v-loading="loading" @changeData="selectionVal">
            <slot>
                <el-table-column label="操作" align="center" width='380px'>
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="handleEdit(scope.$index, scope.row,1)">编辑(关联员工)
                    </el-button>
                      <el-button
                        size="mini"
                        type="primary"
                        class="del"
                        @click="update(scope.$index, scope.row,2)">更新</el-button>
                        <el-button
                          size="mini"
                          type="danger"
                          class="del"
                          @click="handleEdit(scope.$index, scope.row,3)">删除</el-button>
                  </template>
                </el-table-column>
            </slot>
        </tableVue>
    </div>
    <dialogVue title="机构" :dialog="dialog" @close="changeData" :state="false">
        <slot>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
              <el-form-item label="编码" prop="region">
                  <el-input v-model="ruleForm.orgCode" placeholder="请输入编码"></el-input>
              </el-form-item>
              <el-form-item label="上级机构">
                  <el-select v-model="parentOrgId" placeholder="请选择类型" class="set">
                     <el-option label="请选择" value="0"></el-option>
                     <el-option v-for="(val,key) in optionList" :key="key" :label="val.orgName" :value="val.orgId"></el-option>
                 </el-select>
              </el-form-item>
              <el-form-item label="名称" prop="orgName">
                  <el-input v-model="ruleForm.orgName" placeholder="请输入名称"></el-input>
              </el-form-item>
              <el-form-item label="描述" prop="orgDescription">
                  <el-input v-model="ruleForm.orgDescription" placeholder="请输入描述"></el-input>
              </el-form-item>
              <el-form-item class="confirm">
                <el-button type="primary" v-if="btnstate == '2'" @click="submitForm('ruleForm')">创建</el-button>
                <el-button type="primary" v-if="btnstate == '1'" @click="upForm('ruleForm')">更新</el-button>
             </el-form-item>
          </el-form>
        </slot>
    </dialogVue>

    <dialogVue title="机构关联员工" :dialog="orgStaff" @close="changeData" :state="false">
      <div class="">
          <span>选择员工(可搜索)：</span><el-select v-model="value2" filterable placeholder="请选择">
             <el-option
               v-for="item in options"
               :key="item.value"
               :label="item.empName"
               :value="item.empId">
             </el-option>
           </el-select>
      </div>
      <div class="post">
        <span>选择职位(可搜索)：</span><el-select v-model="postValue" filterable placeholder="请选择">
          <el-option
            v-for="(val,key) in postList"
            :key="key"
            :label="val.postName"
            :value="val.postId">
          </el-option>
        </el-select>
      </div>
      <div class="post">
        <span>加入时间：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><el-date-picker
          v-model="date"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </div>
        <el-button type="primary"  class="confirms" @click="relevance">确定</el-button>
    </dialogVue>


    <el-dialog
    title="机构下所有的员工"
    :visible="allorgStaff"
    width="80%">
    <el-table
      ref="multipleTable"
      border
      :data="allorgStaffList.tbody"
      tooltip-effect="dark"
      style="width:100%">

      <el-table-column
        v-for='(item,idx) in allorgStaffList.thead' :label="item.label"  :key='idx' align="center">
        <template slot-scope="scope">{{ scope.row[item.prop] }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.isLeave == 'N'"
            size="mini"
            @click="outOrg(scope.row)">员工退出部门
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <span slot="footer" class="dialog-footer">
      <el-button @click="allorgStaff = false">取 消</el-button>
      <el-button type="primary" @click="allorgStaff = false">确 定</el-button>
    </span>
    </el-dialog>

  </div>
</template>
<script>
    import dialogVue from '@/components/dialog.vue'
    import tableVue from '@/components/alltable.vue'
    import {
      institutionList,
      addOrg ,
      compileOrg,
      delOrg,
      allStaff,
      allPost,
      orgStaff,
      orgAllStaff,
      staffOutOrg
    } from '@/api/institution/institution'
      import checkPermission from "@/utils/permission"; // 权限判断函数
    export default {
      components : {
        tableVue,
        dialogVue
      },
      data () {
        return {
          allorgStaffList : {
            thead : [
              {label:'员工名称',prop:"empName",rowspan:1},
              {label:'员工姓名',prop:"empName",rowspan:1},
              {label:'是否离开部门',prop:"isLeave",rowspan:1},
              {label:'员工账号',prop:"empAccount",rowspan:1},
              {label:'员工职位',prop:"postName",rowspan:1},
              {label:'加入时间',prop:"gmtCreate",rowspan:1},
            ],
            tbody : []
          },
            allorgStaff :false,//机构下面所有的员工弹窗变量
            searchorgId : '',
            date : '',
            orgId :'',
            orgName : '',
            orgCode :'',
            gmtCreate : '',// 创建时间
            postList : [],
            postValue : '',
            value2: '',
            options :[],
            dialog: false,
            loading : false,
            orgStaff:false,//机构关联员工弹窗变量
            condition : '',
            optionList : [],
            updateList : [],
            orgId: '',
            btnstate : '',
            ruleForm : {
              orgCode : '',
              orgName : '',
              orgDescription : '',
            },
           parentOrgId : '',
            rules : {
              name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                  ],
              orgName: [
                    { required: true, message: '请输入内容', trigger: 'blur' },
                  ],
              parameters : [
                    { required: true, message: '请输入内容', trigger: 'blur' },
                  ],
            },
            list : {
              thead : [
                {label:'机构编码',prop:"orgCode",rowspan:1},
                {label:'名称',prop:"orgName",rowspan:1},
                {label:'描述',prop:"orgDescription",rowspan:1},
                {label:'创建时间',prop:"gmtCreate",rowspan:1},
                {label:'更新时间',prop:"gmtUpdate",rowspan:1},
              ],
              tbody : []
            },
            allOrgId : ''//机构id
        }
      },
      mounted () {
        this.getList()
      },
      created () {

      },
      methods : {
        update (idx,item) {//更新机构
          if (checkPermission('org_manager_edit') == true){
               this.btnstate = '1'
               this.dialog = true;
               this.ruleForm.orgCode = item.orgCode;
               this.ruleForm.orgName = item.orgName;
               this.ruleForm.orgDescription = item.orgDescription;
               this.parentOrgId = item.parentOrgId;
               this.orgId = item.orgId
          }
        },
        fmtDate (obj) {
              var date =  new Date(obj);
              var y = 1900+date.getYear();
              var m = "0"+(date.getMonth()+1);
              var d = "0"+date.getDate();
              return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
          },
        getList () {
          this.loading = true
          institutionList().then(res=>{
            if (res.data.code == 'OK') {
              this.loading = false;
              this.list.tbody = res.data.data.records.map(item=>{
                item.gmtCreate = this.switchTime(item.gmtCreate)
                item.gmtUpdate = this.switchTime(item.gmtUpdate)
                return item;
              });
              this.optionList = res.data.data.records;
            }
          })
        },
        dialogs() {
          if (checkPermission('org_manager_add') == true) {
            this.dialog = true;
            this.ruleForm = {};
            this.parentOrgId = ''
            this.btnstate = '2'
          } else {
            this.$message.error('您没有权限新增');
          }
        },
        changeData (val) {
          this.dialog = val
          this.orgStaff = val;
          this.allorgStaff =val;
        },
        selectionVal (val) {
          this.updateList = val;
        },
        handleEdit(idx,item,num){//机构下所有的员工
          if(num == 3) {
              this.dels()
          } else {
            this.allorgStaff = true;
            item.orgId = this.allOrgId;
            this.orgAllStaffList();
          }
        },
        orgAllStaffList () {
          orgAllStaff(this.allOrgId).then(res=>{
            if(res.data.code == 'OK') {
                this.allorgStaffList.tbody = res.data.data.records.map(item=>{
                  item.gmtCreate = this.switchTime(item.gmtCreate);
                  item.isLeave  = item.isLeave == 'Y' ?'是':'否';
                  return item;
                });
            }
          })
        },
        dels () { //批量删除
          if (checkPermission('org_manager_del') == true) {
              if (this.updateList.length > 0) {
                this.$confirm('此操作将永久删除该机构, 是否继续?', '提示', {
                   confirmButtonText: '确定',
                   cancelButtonText: '取消',
                   type: 'warning'
                 }).then(() => {
                   let id = ''
                   this.updateList.map(item=>{
                      id += item.orgId + ','
                   })
                   delOrg(id).then(res=>{
                     if (res.data.code == 'OK') {
                       this.$message.success('删除机构成功');
                       this.getList()
                     } else {
                       this.$message.error(res.data.code);
                     }
                   })
                 }).catch(() => {
                   this.$message({
                     type: 'info',
                     message: '已取消删除'
                   });
                 });
              } else {
                this.$message.error("请选择要删除的机构");
              }
          } else {
              this.$message.error('您没有权限删除');
          }

        },
        submitForm (formName) {
          this.btnstate = '2'
          this.$refs.ruleForm.validate(valid=>{
              if (valid) {
                  let data = {
                    orgCode : this.ruleForm.orgCode,
                    orgName : this.ruleForm.orgName,
                    orgDescription : this.ruleForm.orgDescription,
                    parentOrgId : this.parentOrgId,
                  }
                  addOrg(data).then(res=>{
                    if (res.data.code =='OK') {
                         this.$message.success('新增机构成功');
                         this.dialog = false;
                         this.getList();
                    } else {
                      this.$message.error(res.data.code);
                    }
                  })
              }
          })
        },
        upForm (ruleForm) {//编辑机构确定
          this.$refs.ruleForm.validate(valid=>{
            if (valid) {
              let data = {
                orgCode : this.ruleForm.orgCode,
                orgName : this.ruleForm.orgName,
                orgDescription : this.ruleForm.orgDescription,
                parentOrgId : this.parentOrgId,
                orgId : this.orgId
              }
              compileOrg(data).then(res=>{
                if (res.data.code == 'OK') {
                    this.dialog = false;
                    this.$message.success('编辑成功');
                    this.getList()
                } else {
                    this.$message.error(res.data.code);
                }
              })
            }
          })
        },
        staff () {//机构关联员工
          if (this.updateList.length < 1){
              this.$message.error('请选择机构');
          } else if (this.updateList.length > 1) {
              this.$message.error('只能选择一个机构');
          } else {
            this.orgStaff = true;
            this.value2 = '';
            this.date = '';
            allStaff().then(res=>{
              if (res.data.code =='OK') {
                  this.options = res.data.data.records;
                  allPost().then(res=>{
                     if (res.data.code == 'OK') {
                        this.postList = res.data.data.records;
                     }
                  })
              }
            })
          }
        },
        relevance () {//机构关联员工确定
            var orgId = '';
            this.updateList.map(item=>{
              orgId = item.orgId
            })
            let data = {
              orgId : orgId,
              empId : this.value2,
              post :this.postValue,
              joinTime :this.date
            }
            orgStaff(data).then(res=>{
              if (res.data.code == 'OK') {
                this.$message.success('新增成功');
                this.orgStaff = false;
              } else {
                this.$message.error(res.data.message);
              }
            })
        },
        search () {//搜索
            let data = {
              orgId : this.orgId,
              orgName : this.orgName,
              orgCode :this.orgCode
            }
            institutionList(data).then(res=>{
              if (res.data.code == 'OK') {
                 this.$message.success('搜索成功');
                 this.list.tbody = res.data.data.records.map(item=>{
                   item.gmtCreate = this.switchTime(item.gmtCreate)
                   item.gmtUpdate = this.switchTime(item.gmtUpdate)
                   return item;
                 });
              } else {
                  this.$message.error(res.data.message);
              }
              console.log(res)
            })
        },
        outOrg (item) {//员工退出部门
          if (checkPermission('staff_out_org') == true) {
              var date = this.switchTime(Date.parse(new Date()))
              let data = {
                leaveTime : date,
                empOrgId : item.empOrgId,
              }
              this.delMessage(()=>{
                staffOutOrg(data).then(res=>{
                  if (res.data.code == 'OK') {
                     this.$message.success('员工退出部门成功');
                      this.orgAllStaffList();
                  } else {
                      this.$message.error(res.data.message);
                  }
                })
              })
          } else {
              this.$message.error('您没有权限');
          }
        }
      }
    }
</script>
<style scoped>
  .search {
    width: 100%;
    background-color: #fff;
    padding:20px;
    box-sizing: border-box;
    margin-top: 10px;
    height: 80px;
  }
  .input {
    /* width: 300px; */
    display: flex;
  }
  label {
    line-height: 40px;
    color: #333;
    margin: 0 10px;
  }
  .el-input {
    width:200px;
    height:20px;
  }
  .add {
    margin-top: 10px;
    padding-left: 14px;
  }
  .se {
    margin-left: 20px;
  }
  .table {
    margin-top:10px;
    width: 100%;
  }
  .content label {
    display:inline-block;
    width:134px;
    text-align: justify;
    text-align-last: justify;
    line-height: 0;
    font-size: 18px;
  }
  .content input {
    height:24px;
  }
  .content p {
    margin: 10px 0;
  }
  .del {
    margin-left: 0;
    margin-top:10px;
  }
  .cell {
    text-align: center;
  }
  .confirm {
    position: absolute;
    bottom: -1px;
    right: 100px;
  }
  .dels {
    margin-left: 10px;
  }
  .post {
    margin-top: 10px;
  }
  .el-checkbox+.el-checkbox {
    margin-left: 12px;
    margin-top: 18px;
  }
  .allPost {
    margin: 10px 0;
  }
  .confirms {
    position: absolute;
    bottom: 20px;
    right: 100px;
  }
</style>
